import React, { useState, useEffect } from 'react';
import Post from '../Post'; // 假设这是一个用于显示单个点赞的组件
import { useMatch } from 'react-router-dom';
import { getMyLiked } from '../../api/userApi';

const MyLikes = () => {
  const [likesData, setLikesData] = useState([]);  // 初始化为空数组
  const [loading, setLoading] = useState(true);      // 加载状态
  const [error, setError] = useState(null);          // 错误状态

  // 修正 useMatch 的路径匹配
  const match = useMatch("/mypage/likes/:userId");  
  const userId = match ? match.params.userId : null;   // 从 match 中获取 userId

  useEffect(() => {
    if (userId) {
      setLoading(true);  // 请求开始时设置加载状态
      getMyLiked(userId)
        .then((data) => {
          setLikesData(data);  
          console.log(likesData);
          setLoading(false); 
        })
        .catch((error) => {
          setError('Error fetching followers: ' + error.message);  // 设置错误信息
          setLoading(false);
        });
    }
  }, [userId]);  // 当 userId 改变时重新执行 useEffect

  // 加载中的状态
  if (loading) {
    return <div>Loading...</div>;
  }

  // 错误处理
  if (error) {
    return <div>{error}</div>;
  }

  // 渲染博客数据
  const likes = likesData.map((blog) => ({
      userId:blog.userId,
      userImage: blog.userImage,
      blogImage: blog.blogImage,
      blogId:blog.blogId,
      interestId:blog.interestId,
      title: blog.name,
      author: blog.account,
      content: blog.description,
      time: blog.updateTime,
      likeCount: blog.likesCount,
      commentCount: blog.commentsCount,
      isLiked:blog.isLiked,
      isFollowed:blog.isFollowed,
      isCollected: blog.isCollected, 
    }));

  return (
    <div>
      <ul>
        {likes.map((like, index) => (
          <div key={index}>
            <Post post={like} /> {/* 渲染每个点赞 */}
          </div>
        ))}
      </ul>
    </div>
  );
};

export default MyLikes;
